package com.ibm.cps.sql.expression.json;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ibm.cps.sql.expression.BooleanExpression;
import com.ibm.cps.sql.expression.ConditionCompositionExpression;
import com.ibm.cps.sql.expression.ConditionCompositionExpression.Predicate;

public class ConditionCompositionExpressionDeserializer extends JsonDeserializer<ConditionCompositionExpression>{

	@Override
	public ConditionCompositionExpression deserialize(JsonParser jp,
			DeserializationContext ctxt) throws IOException,
			JsonProcessingException {
		try {
			ObjectMapper mapper = (ObjectMapper) jp.getCodec();  
			ObjectNode root = (ObjectNode) mapper.readTree(jp);
			String predicate = root.get("predicate").asText();
			Predicate p = Predicate.valueOf(predicate);
			String condition1Type = root.get("condition1Type").asText();
			String condition1 = root.get("condition1").toString();
			String condition2Type = root.get("condition2Type").asText();
			String condition2 = root.get("condition2").toString();
			BooleanExpression c1 = (BooleanExpression)mapper.readValue(condition1, Class.forName(condition1Type));
			BooleanExpression c2 = (BooleanExpression)mapper.readValue(condition2, Class.forName(condition2Type));
			System.out.println("inside calc deserializer: " + root);
			return new ConditionCompositionExpression(c1, c2, p);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new IllegalArgumentException(e);
		}
	}

}
